package com.easpeed.user

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.util.Log;
import com.bigyu.utils.Logger
import android.view.Gravity
import android.view.View
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.TextView
import androidx.core.util.Consumer
import androidx.databinding.DataBindingUtil
import androidx.databinding.ObservableBoolean
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.ToastUtils
import com.easpeed.common.CommonConsts
import com.easpeed.common.CommonConsts.deviceId
import com.easpeed.comon.bean.BaseData
import com.easpeed.comon.bean.LoginResult
import com.easpeed.comon.consts.ConstsOpticalData
import com.easpeed.comon.utils.ApiHelper.createLine
import com.easpeed.comon.utils.CacheHelper
import com.easpeed.comon.utils.Line
import com.easpeed.comon.utils.NetHelper
import com.easpeed.comon.utils.Optical
import com.easpeed.elevator.R
import com.easpeed.elevator.bean.LineBean
import com.easpeed.elevator.bean.OpticalBean
import com.easpeed.elevator.databinding.ActivityUserLineManageBinding
import com.easpeed.elevator.utils.CallbackInterface
import com.easpeed.elevator.utils.NoticeDialog
import com.easpeed.elevator.utils.WwAdapter
import com.easpeed.elevator.utils.WwViewHolder
import com.easpeed.user.dialog.UserDialogHelper
import com.easpeed.user.utils.FileHelper
import com.gyf.immersionbar.ImmersionBar
import java.util.UUID

class UserLineManageActivity : UserBaseActivity() {

    var binding: ActivityUserLineManageBinding? = null


    val lineList = ArrayList<LineBean>()

    private val expandLine = HashMap<String, Boolean>()
    private val expandOptical = HashMap<String, Boolean>()


    override fun initView() {


        Logger.e("TAG", "initView:  " + String("设备端启动OTDR成功!".toByteArray(Charsets.UTF_8), Charsets.UTF_8))
        ImmersionBar.with(this)
            .statusBarDarkFont(false) // 设置状态栏字体为深色
            .transparentStatusBar()  // 透明状态栏
            .fitsSystemWindows(true)
            .statusBarColor(R.color.colorTitleBar)
            .init()

        binding = DataBindingUtil.setContentView(this, R.layout.activity_user_line_manage)
        binding?.data = this


        iniView()
        initData()

        initLisenter()
    }

    private fun iniView() {
        initLineView(binding?.recylerviewLine)

    }

    private fun initData() {
//        lineList.clear()
//        lineList.addAll(FileHelper.readLineData(mContext))
//        wwAdapterLine?.notifyDataSetChanged()
        netForLineList()
    }

    private fun initLisenter() {
        binding?.back?.setOnClickListener {
            finish()
        }
        binding?.createLine?.setOnClickListener {
            //创建线路
            createLine("", "新增线路", CallbackInterface { message: String? ->
                readCreateLine(message)
            })
        }
        binding?.manage?.setOnClickListener {
            isManageModel.set(!isManageModel.get())
            wwAdapterLine?.notifyDataSetChanged()
        }
        binding?.manageExit?.setOnClickListener {
            isManageModel.set(!isManageModel.get())
            wwAdapterLine?.notifyDataSetChanged()
        }
    }


    var isManageModel = ObservableBoolean(false)
    private var wwAdapterLine: WwAdapter<LineBean>? = null
    private fun initLineView(recyclerView: RecyclerView?) {
        wwAdapterLine = object : WwAdapter<LineBean>() {
            override fun initRecyclerView(mContext: Context, adapter: WwAdapter<LineBean>) {
                val manager = LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)
                recyclerView?.layoutManager = manager
                recyclerView?.adapter = adapter
                isUseEmpty(true)
            }

            override fun getEmptyLayoutId(): Int {
                return R.layout.user_empty_item_line
            }

            override fun getLayoutId(): Int {
                return R.layout.user_item_line_info
            }

            @SuppressLint("NotifyDataSetChanged")
            override fun convert(holder: WwViewHolder, bean: LineBean, position: Int) {
                holder.setVisible(isManageModel.get(), R.id.delete, R.id.edit)
                holder.setText(R.id.tv_line_name, bean.lineName)
                holder.setActivated(R.id.detail, bean.isExpand)
                holder.setVisible(R.id.recyclerView_optical, bean.isExpand)

                val recyclerViewOptical = holder.getView<RecyclerView>(R.id.recyclerView_optical)

                initLineView(recyclerViewOptical, bean.opticalList as ArrayList<OpticalBean>)

                holder.setOnClickListener(R.id.add, View.OnClickListener { v: View? ->
                    createOptical(bean.opticalList, "新增光缆", null, CallbackInterface { opticalBean: OpticalBean ->
//                        bean.opticalList.add(opticalBean)
//                        wwAdapterLine?.notifyDataSetChanged()
                        val map = HashMap<String, Any?>()
                        map["remark"] = opticalBean.remark
                        map["opticalName"] = opticalBean.name
                        map["fibreLength"] = opticalBean.length
                        map["fibreCodes"] = opticalBean.codeMark
                        map["fibreNum"] = opticalBean.number.toInt()
                        map["hop"] = opticalBean.zjd
                        map["opticalLevel"] = opticalBean.level.toInt()
                        map["lineId"] = bean.lineId
                        map["deviceCode"] = CommonConsts.targetDeviceId
                        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
                        netForCreateOptical(map)
                    })
                })
                holder.setOnClickListener(R.id.edit, View.OnClickListener { v: View? ->
                    createLine(bean.lineName, "编辑线路", CallbackInterface { message: String? ->
                        if (checkLineName(message, true)) {
//                            bean.lineName = message
//                            wwAdapterLine?.notifyDataSetChanged()
                            netForUpdateLine(bean.lineId, "$message")
                        }
                    })
                })

                holder.setOnClickListener(R.id.layout_line_info, View.OnClickListener { v: View? ->
                    if (bean.opticalList.isNullOrEmpty()) {
                        ToastUtils.showShort("该线路暂未发现光缆，请先点击“+”创建")
                    }
                    bean.isExpand = !bean.isExpand
                    expandLine[bean.lineId] = bean.isExpand
                    wwAdapterLine?.notifyDataSetChanged()
                })

                holder.setOnClickListener(R.id.delete, View.OnClickListener { v: View? ->
                    val str = "确定删除 ${bean.lineName} 吗？\n" +
                            "该线路含有${bean.opticalList.size}个相关光缆，将会一起删除。"
                    UserDialogHelper.showNoticeDialog(mContext, "删除线路", str, sureClick = {
//                        lineList.remove(bean)
//                        wwAdapterLine?.notifyDataSetChanged()
                        netForDeleteLine(bean.lineId)
                    })
                })
            }
        }.create(mContext, lineList)
    }


    private fun initLineView(recyclerView: RecyclerView, opticalList: ArrayList<OpticalBean>): WwAdapter<OpticalBean?>? {
        return object : WwAdapter<OpticalBean>() {
            override fun initRecyclerView(mContext: Context, adapter: WwAdapter<OpticalBean>) {
                val manager = LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)
                recyclerView.layoutManager = manager
                recyclerView.adapter = adapter
            }

            override fun getLayoutId(): Int {
                return R.layout.user_item_optical_info
            }

            override fun convert(holder: WwViewHolder, bean: OpticalBean, position: Int) {
                holder.setText(R.id.tv_line_name, bean.name)

                try {
                    val level = ConstsOpticalData.options.getOrNull(bean.level.toInt())
                    holder.setText(R.id.level, level)
                } catch (e: Exception) {
                    e.printStackTrace()
                    holder.setText(R.id.level, "")
                }
                holder.setText(R.id.zjd, bean.zjd)
                holder.setText(R.id.count, bean.number)
                holder.setText(R.id.number, bean.codeMark)
                holder.setText(R.id.length, "${bean.length}km")
                holder.setText(R.id.remark, bean.remark)
                holder.setVisible(isManageModel.get(), R.id.delete, R.id.edit)


                holder.setVisible(R.id.layout_optical_info, bean.isExpand)
                holder.setActivated(R.id.detail, bean.isExpand)


                holder.setOnClickListener(R.id.root, View.OnClickListener { view: View? ->
                    bean.isExpand = !bean.isExpand
                    expandOptical[bean.id] = bean.isExpand
                    wwAdapterLine?.notifyDataSetChanged()
                })

                holder.setOnClickListener(R.id.edit, View.OnClickListener { view: View? ->
                    createOptical(opticalList, "编辑光缆", bean, CallbackInterface { opticalBean: OpticalBean ->
//                        wwAdapterLine?.notifyDataSetChanged()
                        val map = HashMap<String, Any>()
                        map["id"] = opticalBean.id
                        map["remark"] = opticalBean.remark
                        map["opticalName"] = opticalBean.name
                        map["fibreLength"] = opticalBean.length
                        map["fibreCodes"] = opticalBean.codeMark
                        map["fibreNum"] = opticalBean.number.toInt()
                        map["hop"] = opticalBean.zjd
                        map["opticalLevel"] = opticalBean.level.toInt()
                        map["lineId"] = opticalBean.parentId
                        map["deviceCode"] = CommonConsts.targetDeviceId
                        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
                        netForUpdateOptical(map)
                    })
                })

                holder.setOnClickListener(R.id.delete, View.OnClickListener { view: View? ->
                    val str = "确定删除 ${bean.name} 吗？删除后不可撤回。"
                    UserDialogHelper.showNoticeDialog(mContext, "删除光缆", str, sureClick = {
//                        opticalList.remove(bean)
//                        wwAdapterLine?.notifyDataSetChanged()
                        netForDeleteOptical(bean.id)
                    })
                })
            }
        }.create(mContext, opticalList)
    }

    private fun checkLineName(lineName: String?, isEdit: Boolean): Boolean {
        if (TextUtils.isEmpty(lineName)) {
            if (isEdit) {
                ToastUtils.showShort("编辑线路失败 ,请输入线路名称")
            } else {
                ToastUtils.showShort("创建线路失败 ,请输入线路名称")
            }
            return false
        }
//        for (bean in lineList) {
//            if (lineName == bean.lineName) {
//                if (isEdit) {
//                    ToastUtils.showShort("编辑线路失败,线路名称重复")
//                } else {
//                    ToastUtils.showShort("创建线路失败,线路名称重复")
//                }
//                return false
//            }
//        }
        return true
    }

    private fun readCreateLine(lineName: String?) {
        if (TextUtils.isEmpty(lineName)) {
            ToastUtils.showShort("创建线路失败 ,请输入线路名称")
        } else {
            netForCreate(lineName)
        }
    }

    private fun netForCreate(lineName: String?) {
        val map = HashMap<String, Any>()
        map["lineName"] = "$lineName"
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        netHelper.netForCreateLine(true, map, Consumer<BaseData<Line>> {
            if (it.code == 200) {
                ToastUtils.showShort("创建线路成功")
                netForLineList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        })
    }

    private lateinit var netHelper: NetHelper

    private fun netForLineList() {
        val map = HashMap<String, Any>()
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        netHelper.netForLineList(isLoading = true, map, Consumer<BaseData<List<Line>>> {
            if (it.code == 200) {
                lineList.clear()
                it.data?.map {
                    LineBean().apply {
                        this.lineName = it.lineName
                        this.lineId = it.id.toString()
                        this.isExpand = expandLine[it.id.toString()] ?: false
                    }
                }?.let { it1 -> lineList.addAll(it1) }
                wwAdapterLine?.notifyDataSetChanged()
                netForOpticalList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        })
    }

    private fun netForOpticalList() {
        val map = HashMap<String, Any>()
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        lineList.forEach {
            it.opticalList?.clear()
        }
        netHelper.netForListOptical(isLoading = true, map, Consumer<BaseData<List<Optical>>> {
            if (it.code == 200) {
                if (it.data != null) {
                    it.data?.forEach { data ->

                        lineList.find { it.lineId == data.lineId.toString() }?.let {
                            if (it.opticalList == null) {
                                it.opticalList = arrayListOf()
                            }
                            it.opticalList?.add(OpticalBean(data.id.toString()).apply {
                                this.remark = data.remark
                                this.length = data.fibreLength
                                this.codeMark = data.fibreCodes
                                this.number = data.fibreNum.toString()
                                this.zjd = data.hop
                                this.level = data.opticalLevel.toString()
                                this.name = data.opticalName
                                this.parentId = data.lineId.toString()
                                this.isExpand = expandOptical[data.id.toString()] ?: false
                            })
                        }
                    }
                }
                wwAdapterLine?.notifyDataSetChanged()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        })
    }

    private fun netForDeleteOptical(opticalId: String) {
        val map = HashMap<String, Any>()
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        netHelper.netForDeleteOptical(opticalId, map, Consumer<BaseData<String>> {
            if (it.code == 200) {
                ToastUtils.showShort("删除光缆成功")
                netForOpticalList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        }
        )
    }

    private fun netForDeleteLine(lineId: String) {
        val map = HashMap<String, Any>()
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        netHelper.netForDeleteLine(lineId, map, Consumer<BaseData<String>> {
            if (it.code == 200) {
                ToastUtils.showShort("删除线路成功")
                netForLineList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        }
        )
    }


    private fun netForUpdateLine(lineId: String, name: String) {
        val map = HashMap<String, Any>()
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        map["id"] = lineId
        map["lineName"] = name
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        netHelper.netForUpdateLine(map, Consumer<BaseData<String>> {
            if (it.code == 200) {
                ToastUtils.showShort("修改成功")
                netForLineList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        }
        )
    }

    private fun netForUpdateOptical(map: HashMap<String, Any>) {
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        netHelper.netForUpdateOptical(map, Consumer<BaseData<Optical>> {
            if (it.code == 200) {
                ToastUtils.showShort("修改成功")
                netForOpticalList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        }
        )
    }

    private fun netForCreateOptical(map: HashMap<String, Any?>) {
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        netHelper.netForCreateOptical(true, map, Consumer<BaseData<Optical>> {
            if (it.code == 200) {
                ToastUtils.showShort("修改成功")
                netForOpticalList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        }
        )
    }

    /**
     * 创建线路弹框
     */
    private fun createLine(defaultTxt: String, title: String, callbackInterface: CallbackInterface<String>) {
        val dialog = NoticeDialog.Builder(mContext).setLayoutId(R.layout.user_dialog_create_line).setClickBtnDismissDialog(true).setCanCancel(true).setCanceledOnTouchOutside(true).create()
        dialog.setOnclickListener(R.id.close, View.OnClickListener { v: View? ->
            dialog.dismiss()
        })
        dialog.setText(R.id.input, defaultTxt)
        dialog.setText(R.id.title, title)
        dialog.setOnclickListener(R.id.sure, View.OnClickListener { v: View? ->
            val input = (dialog.getView(R.id.input) as TextView).text.toString()
            callbackInterface.onCallback(input)
        })
        dialog.setWidth(ScreenUtils.getScreenWidth())
        dialog.setGravity(Gravity.BOTTOM)
        dialog.show()
    }

    /**
     * 创建光缆
     */
    private fun createOptical(opticalList: MutableList<OpticalBean>, defaultTxt: String, bean: OpticalBean?, callbackInterface: CallbackInterface<OpticalBean>) {
        val dialog = NoticeDialog.Builder(mContext).setLayoutId(R.layout.user_dialog_create_optical).setClickBtnDismissDialog(false).setCanCancel(true).setCanceledOnTouchOutside(true).create()
        dialog.setDialogWith(ScreenUtils.getScreenWidth(), 0)
        dialog.setGravity(Gravity.BOTTOM)
        dialog.setOnclickListener(R.id.close, View.OnClickListener { v: View? ->
            dialog.dismiss()
        })
        if (bean != null) {
            dialog.setText(R.id.name, bean.name)

            try {
                val level = ConstsOpticalData.options.getOrNull(bean.level.toInt())
                dialog.setText(R.id.level, level)
            } catch (e: Exception) {
                e.printStackTrace()
                dialog.setText(R.id.level, "")
            }
            dialog.setText(R.id.zjd, bean.zjd)
            dialog.setText(R.id.count, bean.number)
            dialog.setText(R.id.number, bean.codeMark)
            dialog.setText(R.id.length, bean.length)
            dialog.setText(R.id.remark, bean.remark)
        }
        dialog.setText(R.id.title, defaultTxt)

        val autoCompleteTextView = dialog.getView(R.id.level) as AutoCompleteTextView
        // 准备下拉选项数据
        val adapter: ArrayAdapter<String> = ArrayAdapter<String>(mContext, android.R.layout.simple_dropdown_item_1line, ConstsOpticalData.options)
        autoCompleteTextView.setAdapter(adapter)
        autoCompleteTextView.setOnClickListener(View.OnClickListener { v: View? -> autoCompleteTextView.showDropDown() })


        dialog.setOnclickListener(R.id.reduce, View.OnClickListener { v: View? ->
            val count = dialog.getText(R.id.count)
            if (count != null && !count.isEmpty()) {
                val result = count.toInt() - 1
                dialog.setText(R.id.count, result.toString() + "")
            }
        })
        dialog.setOnclickListener(R.id.add, View.OnClickListener { v: View? ->
            val count = dialog.getText(R.id.count)
            if (count != null && !count.isEmpty()) {
                val result = count.toInt() + 1
                dialog.setText(R.id.count, result.toString() + "")
            }
        })

        dialog.setOnclickListener(R.id.sure, View.OnClickListener { v: View? ->
            for (opticalBean in opticalList) {
                if (bean != null && TextUtils.equals(bean.id, opticalBean.id)) {
                    continue
                }
                if (TextUtils.equals(opticalBean.name, dialog.getText(R.id.name))) {
                    ToastUtils.showShort("光缆不可名称重复")
                    return@OnClickListener
                }
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.name))) {
                ToastUtils.showShort("请输入光缆名称")
                return@OnClickListener
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.level))) {
                ToastUtils.showShort("请选择光缆级别")
                return@OnClickListener
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.zjd))) {
                ToastUtils.showShort("请输入中继段")
                return@OnClickListener
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.count))) {
                ToastUtils.showShort("请输入纤芯数量")
                return@OnClickListener
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.number))) {
                ToastUtils.showShort("请输入纤芯编号")
                return@OnClickListener
            }
            if (dialog.getText(R.id.number).split("；".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size > dialog.getText(R.id.count).toInt()) {
                ToastUtils.showShort("纤芯数量应大于等于纤芯编号数量")
                return@OnClickListener
            }

            if (TextUtils.isEmpty(dialog.getText(R.id.length))) {
                ToastUtils.showShort("请输入纤芯长度")
                return@OnClickListener
            }
            var opticalBean = OpticalBean()
            if (bean != null) {
                opticalBean = bean
            }
            opticalBean.name = dialog.getText(R.id.name)
            opticalBean.level = ConstsOpticalData.options.indexOf(dialog.getText(R.id.level)).toString()
            opticalBean.zjd = dialog.getText(R.id.zjd)
            opticalBean.number = dialog.getText(R.id.count)
            opticalBean.codeMark = dialog.getText(R.id.number)
            opticalBean.length = dialog.getText(R.id.length)
            opticalBean.remark = dialog.getText(R.id.remark)
            callbackInterface.onCallback(opticalBean)
            dialog.dismiss()
        })

        dialog.show()
    }

    override fun onStop() {
        super.onStop()
//        FileHelper.saveLineData(mContext, lineList)
    }
}